package club.kynb.mall.user.service.impl;


import club.kynb.mall.user.api.IUserService;
import club.kynb.mall.user.convert.UserConvertor;
import club.kynb.mall.user.model.dto.UserDTO;
import club.kynb.mall.user.mysql.mapper.UserMapper;
import club.kynb.mall.user.mysql.po.UserPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.pizza.common.web.exception.Errors;
import org.pizza.id.api.IdGenerator;
import org.pizza.util.Checker;
import org.pizza.util.Convertor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Optional;

/**
 * @author kynb_club@163.com
 * @since 2021/6/20 4:59 下午
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements IUserService {

    private final UserMapper userMapper;
    private final IdGenerator idGenerator;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDTO userRegister(UserDTO userDTO) {
        userDTO.setId(idGenerator.nextId(UserPO.class));
        final int insert = userMapper.insert(UserConvertor.convert(UserPO.class, userDTO));
        Checker.ifNotThrow(insert > 0, () -> Errors.SYSTEM.exception("系统异常，注册用户失败"));
        return userDTO;
    }

    @Override
    public Optional<UserDTO> getUserByPhone(String phone, String type) {
        final UserPO userPO = userMapper.selectOne(new QueryWrapper<UserPO>().lambda()
                .eq(UserPO::getPhone, phone)
                .eq(UserPO::getType, type)
        );
        if (Objects.isNull(userPO)) {
            return Optional.empty();
        }
        return Optional.of(UserConvertor.convert(UserDTO.class, userPO));
    }

    @Override
    public void updateUser(UserDTO user) {
        final int update = userMapper.updateById(UserConvertor.convert(UserPO.class, user));
        Checker.ifNotThrow(update>0, () -> Errors.BIZ.exception("系统异常，更新用户失败"));
    }

    @Override
    public void loginSuccess(UserDTO user) {
        this.userMapper.updateById(UserConvertor.convert(UserPO.class, user));
    }

    @Override
    public Optional<UserDTO> getUserById(Long userId) {
        UserPO userPO = userMapper.selectById(userId);
        if (Objects.isNull(userPO)) {
            return Optional.empty();
        }
        return Optional.of(Convertor.convert(UserDTO.class, userPO));
    }


}
